﻿using UnityEngine;
using System.Collections;
using System;
using System.Linq;

/// <summary>
/// 定时器
/// </summary>
public class TimerMgr : Singleton<TimerMgr>
{
    public event Action<float> TimerTickLoop;

    public Timer CreateTimer(float delayTime, int repeat, Action callback)
    {
        var timer = new Timer();
        timer.DelayTime = delayTime;
        timer.RepeatTimes = repeat;
        timer.Callback = callback;

        return timer;
    }

    public Timer CreateTimerAndStart(float delayTime, int repeat, Action callback)
    {
        var timer = CreateTimer(delayTime, repeat, callback);
        timer.Start();
        return timer;
    }

    public Timer CreateFrameBaseTimerAndStart(Action callback)
    {
        var timer = CreateFrameBaseTimer(callback);
        timer.Start();

        return timer;
    }
    public Timer CreateFrameBaseTimer(Action callback)
    {
        var timer = CreateTimer(0, -1, callback);

        return timer;
    }

    public void Loop()
    {
        if (TimerTickLoop != null)
        {
            TimerTickLoop.Invoke(Time.deltaTime);
        }
    }
}

public class Timer
{
    public int RepeatTimes = -1; // 重复次数，小于0无限循环
    public float DelayTime = 0; // 间隔时间
    public Action Callback;

    public bool IsRunning = false;

    private float _passedTime; // 计时器已经过的时间
    private int _repeatedTimes; // 已重复次数
    private bool _bPause = true; // 暂停计时？
    public bool Pause
    {
        get { return _bPause; }
        set
        {
            if (_bPause == value) // 防止多次设置回调
            {
                return;
            }
            if (value == true)
            {
                TimerMgr.instance.TimerTickLoop -= Loop;
            }
            else
            {
                TimerMgr.instance.TimerTickLoop += Loop;
            }
            _bPause = value;
        }
    }


    public void Start()
    {
        reset();

        Pause = false;
        IsRunning = true;
    }

    public void Stop()
    {
        Pause = true;
        IsRunning = false;

        reset();
    }

    private void reset()
    {
        _passedTime = 0;
        _repeatedTimes = 0;
    }

    public void Loop(float deltaTime)
    {
        _passedTime += deltaTime;
        if (_passedTime > DelayTime || Utils.FloatEqual(_passedTime, DelayTime))
        {
            _passedTime -= DelayTime;
            if (RepeatTimes >= 0 && _repeatedTimes >= RepeatTimes)
            {
                Stop();
                return;
            }
            ++_repeatedTimes;
            if (Callback != null)
            {
                Callback.Invoke();
            }

        }
    }
}
